package org.achievement.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.achievement.system.common.RequestResult;
import org.achievement.system.common.annotations.InterfaceAuth;
import org.achievement.system.common.enums.AuthEnum;
import org.achievement.system.common.exception.AuthenticationException;
import org.achievement.system.common.exception.ServiceException;
import org.achievement.system.dao.RoleDao;
import org.achievement.system.dao.UserDao;
import org.achievement.system.pojo.entity.Role;
import org.achievement.system.pojo.entity.User;
import org.achievement.system.pojo.form.UserForm;
import org.achievement.system.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

import static org.achievement.system.controller.CommonController.commonSetting;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    /**
     * 页面
     *
     * @param modelAndView
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping()
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("user");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 获取登录的用户信息
     *
     * @param httpServletRequest
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/getUser")
    public RequestResult getUser(HttpServletRequest httpServletRequest) {
        String username = (String) httpServletRequest.getSession().getAttribute("username");
        if (username == null) {
            throw new AuthenticationException("登录已过期，请重新登录！");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("username", username);
        User user = userDao.selectOne(queryWrapper);
        if (user == null) {
            throw new ServiceException("错误，没有该用户！");
        }
        // 清除密码
        user.setPassword("");

        // 查询角色
        Role role = roleDao.selectById(user.getRoleId());

        HashMap<String, Object> resData = new HashMap<>();
        resData.put("user", user);
        resData.put("role", role);
        return RequestResult.success(resData);
    }

    /**
     * 获取学生列表
     *
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/getStudentList")
    public RequestResult getStudentList() {
        List<User> userList = selectUserListByRole("学生");
        return RequestResult.success(userList);
    }

    /**
     * 获取教师列表
     *
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/getTeacherList")
    public RequestResult getTeacherList() {
        List<User> userList = selectUserListByRole("教师");
        return RequestResult.success(userList);
    }

    /**
     * 代码抽取
     *
     * @param roleName
     * @return
     */
    private List<User> selectUserListByRole(String roleName) {
        Role role = roleDao.selectOne(new QueryWrapper<Role>().eq("name", roleName).last("LIMIT 1"));
        if (role == null) {
            throw new ServiceException("未查询到" + roleName + "角色！");
        }
        List<User> users = userService.list(new QueryWrapper<User>().eq("role_id", role.getId()));
        if (users != null && users.size() > 0) {
            for (User user : users) {
                user.setPassword(null);
            }
        }
        return users;
    }

    /**
     * 查询
     *
     * @param userForm
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/list")
    public RequestResult list(@RequestBody UserForm userForm) {
        return userService.list(userForm);
    }

    /**
     * 增加
     *
     * @param user
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/add")
    public RequestResult add(@RequestBody User user) {
        if (user == null) {
            throw new ServiceException("不能提交空数据！");
        }
        if (StrUtil.isBlank(user.getUsername())) {
            throw new ServiceException("用户名不能为空！");
        }
        if (StrUtil.isBlank(user.getPassword())) {
            throw new ServiceException("密码不能为空！");
        }
        if (user.getRoleId() == null) {
            throw new ServiceException("角色不能为空！");
        }
        long count = userService.count(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        if (count > 0) {
            throw new ServiceException("用户名已存在！");
        }
        boolean save = userService.save(user);
        if (! save) {
            throw new ServiceException("保存失败！");
        }
        return RequestResult.success("提交成功！");
    }

    /**
     * 修改
     *
     * @param user
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/edit")
    public RequestResult edit(@RequestBody User user) {
        if (user == null) {
            throw new ServiceException("不能提交空数据！");
        }
        if (StrUtil.isBlank(user.getUsername())) {
            throw new ServiceException("用户名不能为空！");
        }
        if (StrUtil.isBlank(user.getName())) {
            throw new ServiceException("姓名不能为空！");
        }
        if (user.getRoleId() == null) {
            throw new ServiceException("角色不能为空！");
        }
        User dbUser = userService.getOne(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        if (dbUser.getId() != user.getId() &&
                user.getUsername().equals(dbUser.getUsername())) {
            throw new ServiceException("用户名已存在！");
        }
        boolean save = userService.updateById(user);
        if (! save) {
            throw new ServiceException("保存失败！");
        }
        return RequestResult.success("提交成功！");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER})
    @RequestMapping("/delete")
    public RequestResult delete(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("请先选择！");
        }
        boolean removed = userService.removeBatchByIds(ids);
        if ( ! removed) {
            throw new ServiceException("删除失败！");
        }
        return RequestResult.success("删除成功！");
    }

}